package com.example.myapplication.fragments.fragmentsview;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.example.myapplication.R;
import com.example.myapplication.baidumap.testActivity;
import com.example.myapplication.baidumap.utils.PoiOverlay;
import com.example.myapplication.baidumap.utils.WalkingRouteOverlay;
import com.example.myapplication.databinding.FragmentWarningBinding;

public class WarningFragment extends Fragment {

    private FragmentWarningBinding binding;

    private MapView mMapView = null;

    public static BaiduMap mBaiduMap;

    public MyLocationListener myLocationListener;

    public LocationClient mLocationClient;

    public LocationClientOption option;

    private LatLng myposition;

    private RoutePlanSearch mSearch;

    private GeoCoder mCoder;

    private PoiSearch mPoiSearch;

    String city;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater,R.layout.fragment_warning,container,false);
        binding.imageView36.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(),testActivity.class));
            }
        });
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView = binding.bmapView;
        mapinit();//地图控件初始化
        codeInit();
        maplisenerinit();//地图监听初始化
        roadsearchInit();//步行线路规划初始化
        Poisearch();//Poi搜索初始化
    }

    private void Poisearch() {
        mPoiSearch = PoiSearch.newInstance();
        OnGetPoiSearchResultListener listener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    mBaiduMap.clear();

                    //创建PoiOverlay对象
                    PoiOverlay poiOverlay = new PoiOverlay(mBaiduMap);

                    //设置Poi检索数据
                    poiOverlay.setData(poiResult);

                    //将poiOverlay添加至地图并缩放至合适级别
                    poiOverlay.addToMap();
                    poiOverlay.zoomToSpan();
                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }

            //废弃
            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }
        };
        mPoiSearch.setOnGetPoiSearchResultListener(listener);
    }

    public void codeInit() {
        mCoder = GeoCoder.newInstance();
        OnGetGeoCoderResultListener cistener = new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                    Log.i("xx", "没有找到检索结果");
                    return;
                } else {
                    //详细地址
                    String address = reverseGeoCodeResult.getAddress();
                    //行政区号
                    int adCode = reverseGeoCodeResult.getCityCode();
                    city = reverseGeoCodeResult.getAddressDetail().city;
                    Log.i("xx", "我的城市:" + city);
                }
            }
        };
        mCoder.setOnGetGeoCodeResultListener(cistener);
    }

    public void roadsearchInit() {
        //创建路线规划检索实例
        mSearch = RoutePlanSearch.newInstance();
        //创建路线规划检索结果监听器
        OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
                //创建WalkingRouteOverlay实例
                WalkingRouteOverlay overlay = new WalkingRouteOverlay(mBaiduMap);
                if (walkingRouteResult.getRouteLines().size() > 0) {
                    //获取路径规划数据,(以返回的第一条数据为例)
                    //为WalkingRouteOverlay实例设置路径数据
                    overlay.setData(walkingRouteResult.getRouteLines().get(0));
                    //在地图上绘制WalkingRouteOverlay
                    overlay.addToMap();
                }
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            }
        };
        //设置路线规划检索监听器
        mSearch.setOnGetRoutePlanResultListener(listener);
    }

    /**
     * 定位监听
    *通过继承抽象类BDAbstractListener并重写其onReceieveLocation方法来获取定位数据，
     * 并将其传给MapView。
    */
    public class MyLocationListener extends BDAbstractLocationListener {
        int i = 0;
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            myposition = new LatLng(location.getLatitude(), location.getLongitude());

            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(myposition));

            mCoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(myposition)
                    // 设置是否返回新数据 默认值0不返回，1返回
                    .newVersion(0)
                    // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                    .radius(500));
            if (i == 0) {
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(myposition));
                i++;
            }
        }
    }

    //标记点绘制
    public void sign(LatLng point) {
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.sign);

        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    //地图监听
    private void maplisenerinit() {
        //设置标记点单击监听
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            //marker被点击时回调的方法
            //若响应点击事件，返回true，否则返回false
            //默认返回false
            @Override
            public boolean onMarkerClick(Marker marker) {
//                InfoWindow infoWindow=new InfoWindow("aa")
//                mBaiduMap.showInfoWindow();
                Log.i("xx", marker.getTitle() + marker.getPosition().toString());
                return false;
            }
        });

        binding.imageView37.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key=binding.textView36.getText().toString();
                if (city != "") {
                    if (key != "") {
                        mPoiSearch.searchInCity(new PoiCitySearchOption()
                                .city(city) //必填
                                .keyword(key) //必填
                                .pageNum(10));
                    } else {
                        Log.i("xx", "未输入搜索内容");
                        return;
                    }
                }else {
                    Log.i("xx", "未定位到城市");
                    return;
                }
            }
        });

        //地图点击事件
        BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
            /**
             * 地图单击事件回调函数
             *
             * @param point 点击的地理坐标
             */
            @Override
            public void onMapClick(LatLng point) {
                mBaiduMap.clear();
                sign(point);
                PlanNode stNode = PlanNode.withLocation(myposition);
                PlanNode enNode = PlanNode.withLocation(point);
                if (getDistance(myposition, point) < 50) {
                    mSearch.walkingSearch((new WalkingRoutePlanOption())
                            .from(stNode)
                            .to(enNode));
                } else {
                    Log.i("xx", "超过50公里");
                }
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));
            }

            /**
             * 地图内 Poi 单击事件回调函数
             *
             * @param mapPoi 点击的 poi 信息
             */
            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
                mBaiduMap.clear();
                Log.i("xx", mapPoi.getName() + mapPoi.getPosition());
                PlanNode stNode = PlanNode.withLocation(myposition);
                PlanNode enNode = PlanNode.withLocation(mapPoi.getPosition());
                if (getDistance(myposition, mapPoi.getPosition()) < 50) {
                    mSearch.walkingSearch((new WalkingRoutePlanOption())
                            .from(stNode)
                            .to(enNode));
                } else {
                    Log.i("xx", "超过50公里");
                }
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(mapPoi.getPosition()));
            }
        };
        //设置地图单击事件监听
        mBaiduMap.setOnMapClickListener(listener);
    }

    //计算两点距离
    public static double getDistance(LatLng latLng1, LatLng latLng2) {
        // 维度
        double lat1 = (Math.PI / 180) * latLng1.latitude;
        double lat2 = (Math.PI / 180) * latLng2.latitude;

        // 经度
        double lon1 = (Math.PI / 180) * latLng1.longitude;
        double lon2 = (Math.PI / 180) * latLng2.longitude;

        // 地球半径
        double R = 6371.004;

        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

        return d;
    }

    //定位初始化
    private void mapinit() {
        //获取地图控件引用
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        //设置地图缩放比例
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(17));
        //定位初始化
        mLocationClient = new LocationClient(getActivity());
        //通过LocationClientOption设置LocationClient相关参数
        option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        //设置locationClientOption
        mLocationClient.setLocOption(option);
        //注册LocationListener监听器
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //百度城市热力图
//        mBaiduMap.setBaiduHeatMapEnabled(true);
        //实时路况图图层
        mBaiduMap.setTrafficEnabled(true);
        //开启地图定位图层
        mLocationClient.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;

        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        mSearch.destroy();
        mCoder.destroy();
    }
}